<?php
namespace App\Admin\Controllers\Reimburse;

use App\Admin\Actions\Reimburse\ApplyCommission;
use App\Admin\Actions\Reimburse\ApplyFirst;
use App\Admin\Actions\Reimburse\ApplyOnce;
use App\Admin\Actions\Reimburse\ApplySecond;
use App\Admin\Actions\Reimburse\ImportA;
use App\Admin\Ajax\Reimburse\ApplyAjax;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\Currency;
use App\Models\Product\ProductClassify;
use App\Models\Reimburse\ReimburseApply;
use App\Models\Reimburse\ReimburseDetail;
use App\Models\Reimburse\ReimbursePaid;
use App\Util\ListPermission;
use App\Util\User;
use Encore\Admin\Admin as RAdmin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Database\Eloquent\Collection;
use App\Admin\Renderable\Reimburse\ShowApply;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
class ApplyController extends AdminController{

    protected $title = '返款申请';

    protected function grid()
    {
        RAdmin::script($this->_script());
        $grid = new Grid(new ReimburseApply());
        $grid = ListPermission::gridCountry($grid);
        $grid->model()->orderBy('id', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $paid = [1=>null,2=>null,3=>null,4=>null];
                $paid_4 = null;
                foreach($item->paid->sortBy('order_by') as $itemPaid){
                    $paid[$itemPaid->order_by] = $itemPaid;
                    if($itemPaid->order_by == 4){
                        $paid_4 = $itemPaid;
                    }
                }
                $item->paid_status_4 = $paid_4->paid_status ?? '';
                $item->currency_code_4 = $paid_4->currency_code ?? '';
                $item->paid_method_4 = $paid_4->paid_method ?? '';
                $item->paid_account_no_4 = $paid_4->paid_account_no ?? '';
                foreach($paid as $k => $_paid){
                    $item->{'_paid_'.$k} = $_paid;
                }
                $item->check = '查看';
            }
            return $collection;
        });
        $grid->column('check','操作')->modal('付款明细',ShowApply::class);
        $grid->column('created_at','创建时间');
        $grid->column('apply_status','申请状态')->using(ReimburseApply::$_applyStatus);
        $grid->column('audit_status','审核状态')->using(ReimburseApply::$_auditStatus);
        $grid->column('paid_status','付款状态')->using(ReimburseApply::$_paidStatus);
        $grid->column('fee_type','费用类型')->using(ReimburseApply::$_feeType);
        $grid->column('r_type','刷单类型')->using(ReimburseApply::$_rType);
        $grid->column('order_no','订单号/费用描述')->display(function ($value, $column){
            if ($this->apply_status == 1) {
                return $column->editable();// 否则显示为editable
            }
            return $value;
        });
        $grid->column('country.country','国家');
        $grid->column('seller_id','销售员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('seller_sku','亚马逊SKU');
        $grid->column('sku.psku_code','公司SKU');
        $grid->column('sku.psku_cn','产品名称');
        $grid->column('skuClassify.title','品类');
        $grid->column('paid_method','支付方式')->using(ReimburseApply::$_paidMethod);
        $grid->column('paid_account_no','支付账号')->display(function ($value, $column){
            if ($this->paid_status == 1) {
                return $column->editable();
            }
            return $value;
        });
        $grid->column('paid_type','返款类型')->using(ReimburseApply::$_paidType);
        $grid->column('currency_code','币种')->display(function ($value, $column){
            if ($this->paid_status == 1) {
                return $column->editable('select',Currency::options());
            }
            return Currency::getNameByCode($value);
        });
        $grid->column('order_atten','订单联系人')->display(function ($value, $column){
            if ($this->paid_status != 3) {
                return $column->editable();
            }
            return $value;
        });
        $grid->column('remarks','备注')->editable();
        $grid->column('review_status','留评状态')->editable('select',ReimburseApply::$_reviewStatus);
        $grid->column('review_link','留评链接')->view('reimburse.apply.link');
        $grid->column('review_at','留评时间')->date();
        $grid->column('currency_code_4','佣金币种')->display(function ($value, $column){
            if($this->paid_type == 3){
                if ($this->paid_status_4 != 3) {
                    return $column->editable('select',Currency::options());
                }
                return Currency::getNameByCode($value);
            }
            return '';
        });
        $grid->column('paid_method_4','佣金支付方式')->display(function ($value, $column){
            if($this->paid_type == 3){
                if ($this->paid_status_4 != 3) {
                    return $column->editable('select',ReimburseApply::$_paidMethod);
                }
                return ReimburseApply::$_paidMethod[$value];
            }
            return '';
        });
        $grid->column('paid_account_no_4','佣金账号')->display(function ($value, $column){
            if($this->paid_type == 3){
                if ($this->paid_status_4 != 3) {
                    return $column->editable();
                }
                return $value;
            }
            return '';
        });

        $grid->column('_paid_1','一次性返款')->view('reimburse.apply.paid');
        $grid->column('_paid_2','首次返款')->view('reimburse.apply.paid');
        $grid->column('_paid_3','二次返款')->view('reimburse.apply.paid');
        $grid->column('_paid_4','佣金')->view('reimburse.apply.paid');

        $grid->disableActions();
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ImportA());
        });
        $grid->batchActions(function ($batch) {
            $batch->add(new ApplyOnce());
            $batch->add(new ApplyFirst());
            $batch->add(new ApplySecond());
            $batch->add(new ApplyCommission());
        });
        $grid->fixColumns(2, -4);
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('reimburse/apply-download'));
        });
        $grid->paginate(10);
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->like('paid_account_no', '支付账号');
                $filter->where(function ($query) {
                    $query->whereIn('order_no', explode(',',"{$this->input}"));
                }, '订单号','orderNo');
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('fee_type','费用类型')->select(ReimburseApply::$_feeType);
                $filter->equal('r_type','刷单类型')->select(ReimburseApply::$_rType);
                $filter->equal('paid_status','付款状态')->select(ReimburseApply::$_paidStatus);
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
                $filter->equal('country_id','国家')->select(AmazonCountry::options());
                $filter->equal('seller_id','销售')->select(User::getSellerOptions());
            });
        });
        return $grid;
    }

    protected function __options(){
        $options = json_encode([
            'emptytext'  => '<i class="fa fa-pencil"></i>',
            'mode' => 'inline',
            'name' => 'review_link',
        ]);

        return substr($options, 0, -1).<<<'STR'
    ,
    "success":function(response, newValue){
        if (typeof response === 'object') {
            if (response.status){
                $.admin.toastr.success(response.message, '', {positionClass:"toast-top-center"});
            } else {
                $.pjax.reload('#pjax-container');
                $.admin.toastr.error(response.message, '', {positionClass:"toast-top-center"});
            }
        }
    }
}
STR;
    }

    protected function __paidAmountOptions(){
        $options = json_encode([
            'emptytext'  => '<i class="fa fa-pencil"></i>',
            'mode' => 'inline',
            'name' => 'paid_amount',
            'showbuttons' => false,
        ]);

        return substr($options, 0, -1).<<<'STR'
    ,
    "success":function(response, newValue){
        if (typeof response === 'object') {
            if (response.status){
                $.admin.toastr.success(response.message, '', {positionClass:"toast-top-center"});
            } else {
                $.pjax.reload('#pjax-container');
                $.admin.toastr.error(response.message, '', {positionClass:"toast-top-center"});
            }
        }
    }
}
STR;
    }

    protected function _script()
    {
        $token = csrf_token();

        $options = $this->__options();
        $paidAmountOptions = $this->__paidAmountOptions();

        return <<<EOT
$('.grid-editable-review_link').editable($options);
$('.grid-editable-paid_amount').editable($paidAmountOptions);

var _ajaxConfirm = function(action,param,resolve){
    $.ajax({
        method: 'post',
        url: '/xqc/reimburse/apply-ajax',
        data: {
            _token: "{$token}",
            action: action,
            param: param
        },
        success: function (data) {
            resolve(data);
        }
    });
};
//申请
$('.grid-check-apply').unbind('click').click(function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    $.ajax({
        method: 'post',
        url: '/xqc/reimburse/apply-ajax',
        data: {
            _token: "{$token}",
            param:id,
            action:'apply'
        },
        success: function (data) {
            if (typeof data === 'object') {
                if (data.status) {
                    $.pjax.reload('#pjax-container');
                    toastr.success('提交成功 !');
                } else {
                    swal(data.message, '', 'error');
                }
            }
        }
    });
});
//撤回
$('.grid-check-revoke').unbind('click').click(function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    swal({
        title: "确定撤回？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            return new Promise(function(resolve) {
                _ajaxConfirm('revoke',id,resolve)
            });
        }
    }).then(function(result) {
        var data = result.value;
        if (typeof data === 'object') {
            if (data.status) {
                toastr.success('提交成功 !');
                $.pjax.reload('#pjax-container');
            } else {
                swal(data.message, '', 'error');
            }
        }
    });
});
EOT;
    }

    public function update($id)
    {
        try{
            $name = Request::get('name');
            $value = trim(Request::get('value'));
            DB::beginTransaction();
            $ra = ReimburseApply::query()->find($id);
            if(in_array($name,['review_status','review_link','review_at','order_no','paid_account_no','currency_code','order_atten','remarks'])){
                $ra->{$name} = $value;
                $flag1 = $ra->save();
                if(!$flag1){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '操作失败']);
                }
                if(in_array($name,['paid_account_no','currency_code'])){
                    $flag2 = ReimbursePaid::query()
                        ->where('reimburse_no',$ra->reimburse_no)
                        ->where('order_by','<',4)
                        ->update([$name => $value]);
                    if(!$flag2){
                        DB::rollBack();
                        return response()->json(['status' => false, 'message' => '操作失败']);
                    }
                }
                if(!in_array($name, ['review_status','review_link','review_at','order_atten'])){
                    $flag3 = ReimburseDetail::query()
                        ->where('reimburse_no',$ra->reimburse_no)
                        ->update([$name => $value]);
                    if(!$flag3){
                        DB::rollBack();
                        return response()->json(['status' => false, 'message' => '操作失败']);
                    }
                }
            }else{
                $rp = ReimbursePaid::query()
                    ->where('reimburse_no',$ra->reimburse_no)
                    ->where('order_by',4)
                    ->first();
                if(!$rp){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '操作失败']);
                }
                if($name == 'currency_code_4'){
                    $rp->currency_code = $value;
                }else if($name == 'paid_method_4'){
                    $rp->paid_method = $value;
                }else if($name == 'paid_account_no_4'){
                    $rp->paid_account_no = $value;
                }
                $flag4 = $rp->save();
                if(!$flag4){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '操作失败']);
                }
            }
            DB::commit();
            return response()->json(['status' => true, 'message' => '操作成功！']);
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new ApplyAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function create(Content $content)
    {
        return $content->header('返款申请')
            ->description('新增')
            ->body(view('reimburse.apply-add.index'));
    }

    public function destroy($idStr){
        try{
            DB::beginTransaction();
            $message = [];
            $ras = ReimburseApply::query()->find(explode(',',$idStr));
            foreach ($ras as $ra){
                if($ra->paid_status > 1){
                    $message[] = $ra->reimburse_no;
                    continue;
                }
                $ra->delete();
            }
            DB::commit();
            return response()->json([
                'status' => empty($message) ? true : false,
                'message' => empty($message) ? '操作成功！' : implode(PHP_EOL,$message).'已付款勿删除'
            ]);
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ReimburseApply::query()->orderBy('id', 'DESC');
        $query = ListPermission::country($query);
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'paid_account_no'){
                $query->where(function ($query) use($_filter){
                    $query->where('paid_account_no', 'like', "%{$_filter}%");
                });
            }
            if($key == 'orderNo'){
                $query->whereIn('order_no', explode(',',"{$_filter}"));
            }
            if(in_array($key,['fee_type','r_type','paid_status','country_id','seller_id'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        ReimburseApply::exeDownload($query);
    }
}
